package com.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class AddUserServlet
 */
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final static String DATASOURCE_NAME = "jdbc/FlyGreenwichAirline";
	
	private DataSource datasource;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("adminUsername");
		String password = request.getParameter("adminPassword");
		
		System.out.println("Admin username: "+username);
		System.out.println("Admin password: "+password);
		
		java.sql.Connection con=null;

    	String query = "INSERT INTO admin (username,password) values (?,?);";
    	
    	try{
    		
    		Context env = (Context) new InitialContext().lookup("java:comp/env");
			datasource = (DataSource) env.lookup(DATASOURCE_NAME);
    		con = datasource.getConnection();
    		
    		java.sql.PreparedStatement pst = con.prepareStatement(query);
    		
    			pst.setString(1, username);
    			pst.setString(2, password);
    			pst.executeUpdate();
            
    	}catch(SQLException e){
    		e.printStackTrace();
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		try{
    			if (con != null) con.close();
    		}catch(SQLException ignored){
    		ignored.printStackTrace();
    		}
    	}
    	
    	request.setAttribute("add", "yes");
    
    	String nextJSP = "/admin/index.jsp";
    	RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
    	dispatcher.forward(request,response);
	}

}
